import * as path from 'path';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
// 获取当前文件的目录路径（ES模块兼容方式）
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// 读取syscall.txt文件中的系统调用列表
function readSyscallList() {
  // syscall.txt文件位于blink-ts目录下
  const filePath = path.join(__dirname, '../syscall.txt');
  console.log(`Reading syscall.txt from: ${filePath}`);
  const content = fs.readFileSync(filePath, 'utf8');
  
  // 提取系统调用列表（假设系统调用在特定的行范围内）
  const syscalls: string[] = [];
  const lines = content.split('\n');
  let capture = false;
  
  for (const line of lines) {
    // 查找"已实现的系统调用列表（按字母顺序排列）"这一行
    if (line.includes('已实现的系统调用列表（按字母顺序排列）')) {
      capture = true;
      continue;
    }
    
    // 如果是空行或包含其他内容则跳过
    if (!capture || !line.trim() || line.trim().startsWith('#')) {
      continue;
    }
    
    // 提取系统调用名称
    const syscallName = line.trim();
    if (syscallName) {
      syscalls.push(syscallName);
    }
  }
  
  return syscalls;
}

// 读取SystemCallHandler.ts文件中已实现的系统调用
function readImplementedSyscalls() {
  const filePath = path.join(__dirname, '../src/syscall/SystemCallHandler.ts');
  console.log(`Reading SystemCallHandler.ts from: ${filePath}`);
  const content = fs.readFileSync(filePath, 'utf8');
  
  // 提取已实现的系统调用函数名
  const implementedSyscalls: string[] = [];
  const regex = /private sys([A-Z][a-zA-Z0-9_]*)\(/g;
  let match;
  
  while ((match = regex.exec(content)) !== null) {
    // 将系统调用函数名转换为小写形式（去掉sys前缀并转小写）
    const syscallName = match[1].toLowerCase();
    implementedSyscalls.push(syscallName);
  }
  
  return implementedSyscalls;
}

// 比较两个列表，找出尚未实现的系统调用
function findUnimplementedSyscalls() {
  const syscallList = readSyscallList();
  const implementedSyscalls = readImplementedSyscalls();
  
  const unimplementedSyscalls: string[] = [];
  
  for (const syscall of syscallList) {
    // 检查系统调用是否已实现
    if (!implementedSyscalls.includes(syscall)) {
      unimplementedSyscalls.push(syscall);
    }
  }
  
  return {
    total: syscallList.length,
    implemented: implementedSyscalls.length,
    unimplemented: unimplementedSyscalls,
    unimplementedCount: unimplementedSyscalls.length
  };
}

// 运行脚本
const result = findUnimplementedSyscalls();
console.log(`Total syscalls in syscall.txt: ${result.total}`);
console.log(`Implemented syscalls: ${result.implemented}`);
console.log(`Unimplemented syscalls: ${result.unimplementedCount}`);
console.log(`Unimplemented syscalls list:`);
console.log(result.unimplemented.join('\n'));